<template>
  <div v-if="isRouterAlive">
    <el-row :gutter="20">
      <el-col :span="6">
        <p role="button" style="padding-left:25px" @click="setSort('name')">
          <i v-if="sortby == 'name'" class="el-icon-sort" />
          文件名
        </p>
      </el-col>
      <el-col :span="6">
        <p role="button" @click="setSort('size')">
          <i v-if="sortby == 'size'" class="el-icon-sort" />
          文件大小
        </p>
      </el-col>
      <el-col :span="6">
        <p role="button" @click="setSort('modified')">
          <i v-if="sortby == 'modified'" class="el-icon-sort" />
          最近一次修改时间
        </p>
      </el-col>
    </el-row>
    <item
      v-for="(i,index) in items"
      :key="i.name"
      :index="index"
      :size="i.size"
      :is-dir="i.isDir"
      :modified="i.modified"
      :name="i.name"
      :url="i.url"
      :type="i.type"
    />

  </div>
</template>

<script>
import { listCloudFile } from '@/api/file'
import { mapGetters } from 'vuex'
import Item from './ListingItem'

export default {
  components: {
    Item
  },
  data: function() {
    return {
      sortby: 'name',
      items: [
        {
          index: 1,
          size: 20,
          isDir: true,
          modified: '2020-6-20 16:40',
          name: 'dir',
          url: 'url1',
          type: 'dir'
        },
        {
          index: 2,
          size: 20,
          isDir: false,
          modified: '2020-6-20 16:30',
          name: 'file',
          url: 'url2',
          type: 'file'
        }
      ],
      isRouterAlive: true
    }
  },
  computed: {
    // 获得用户名， uncheck
    ...mapGetters([
      'name'
    ])
  },
  provide() {
    return {
      reload: this.reload
    }
  },
  created() {
    listCloudFile({
      name
    }).then(res => {
      console.log(res)
      this.items = res
    }).catch(err => {
      console.log(err)
      this.$notify({
        message: 'error happed'
      })
    })
  },
  methods: {
    setSort(val) {
      if (val === this.sortby) { this.items.reverse() } else {
        this.sortby = val
        this.items.sort((a, b) => {
          if (a.type !== b.type) { return a.type === 'dir' }
          return a[val] - b[val]
        })
      }
    },
    reload() {
      this.isRouterAlive = false
      this.$nextTick(() => {
        listCloudFile({
          name
        }).then(res => {
          console.log(res)
          this.items = res
        }).catch(err => {
          console.log(err)
          this.$notify({
            message: 'error happed'
          })
        }).finally(() => {
          this.isRouterAlive = true
        })
      })
    }
  }
}
</script>
